package com.hanserwei.han_picture.aop;

import com.hanserwei.han_picture.annotation.AuthCheck;
import com.hanserwei.han_picture.domain.entity.po.User;
import com.hanserwei.han_picture.enums.ResponseCodeEnum;
import com.hanserwei.han_picture.enums.UserRoleEnum;
import com.hanserwei.han_picture.service.UserService;
import com.hanserwei.han_picture.utils.ThrowUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Component
@Aspect
@RequiredArgsConstructor
public class AuthInterceptor {
    private final UserService userService;

    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        // 1.获取到当前登录用户
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        User loginUser = userService.getLoginUser(request);
        // 2.获取注解权限枚举
        String requiredRole = authCheck.requiredRole();
        UserRoleEnum requiredRoleEnum = UserRoleEnum.getEnumByValue(requiredRole);
        // 3.校验权限
        // 没有注解，则直接放行
        if (requiredRoleEnum == null) {
            return joinPoint.proceed();
        }
        // 4.获取当前用户权限
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(loginUser.getUserRole());
        // 5.权限校验
        ThrowUtils.throwIf(userRoleEnum == null, ResponseCodeEnum.FORBIDDEN_ACCESS, "无权访问！");
        // 6.需要管理员权限，需判断当前用户权限是否为管理员
        ThrowUtils.throwIf(UserRoleEnum.ADMIN.equals(requiredRoleEnum) && !userRoleEnum.equals(UserRoleEnum.ADMIN), ResponseCodeEnum.FORBIDDEN_ACCESS, "无权访问！");
        // 7.放行
        return joinPoint.proceed();
    }
}
